﻿using EDoc2.ApiClientManage.Organization;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using YMImportWeb.Common;
using YMImportWeb.DAL;
using YMImportWeb.Model;

namespace YMImportWeb
{
    /// <summary>
    /// import 的摘要说明
    /// </summary>
    public class import : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            //eodc2Api
            OrganizationApiProvider orgApi = new OrganizationApiProvider();            
            LogHelper.Info("导入开始");
            //返回信息
            bool success = true;
            string msg = string.Empty;

            //获取token
            string token = CookieHelper.GetCookieValue("token");
            LogHelper.Info("token：" + token);
            if (!string.IsNullOrEmpty(token))
            {
                //根据token获取用户 return：Result=0成功,EDocUserInfo用户信息
                var orgResult = orgApi.GetUserInfoByToken(token);
                LogHelper.Info("orgResult.Result：" + orgResult.Result);
                if (orgResult.Result == 0)
                {
                    LogHelper.Info("orgResult.UserInfo.UserId：" + orgResult.UserInfo.UserId);
                    //根据UserId获取用户表信息
                    OrgUser orgUser = DataDAL.GetOrgUserByUserId(orgResult.UserInfo.UserId);
                    LogHelper.Info("orgUser：" + orgUser.user_name + "(" + orgUser.user_id + ")");
                    if (orgUser != null)
                    {
                        //获取上传的文件
                        HttpPostedFile filePost = context.Request.Files["filed"];
                        LogHelper.Info("filePost.ContentLength：" + filePost.ContentLength);
                        #region 导入Excel给数据赋值
                        if (filePost != null && filePost.InputStream != null && filePost.ContentLength > 0)
                        {
                            //实例化帮助类
                            ExcelAccessor excel = new ExcelAccessor();
                            //读取Excel
                            List<ImportBackDataModel> oldDataList = excel.ReadExcelByStream<List<ImportBackDataModel>>(filePost.InputStream);
                            LogHelper.Info("oldDataList：" + JsonConvert.SerializeObject(oldDataList));
                            List<ImportBackDataModel> dataList = new List<ImportBackDataModel>();
                            //读取Excel会读到一些空行数据，这里做一些条件筛选
                            foreach (var item in oldDataList)
                            {
                                if (!string.IsNullOrEmpty(item.归档人工号) || !string.IsNullOrEmpty(item.文件名称) 
                                    || !string.IsNullOrEmpty(item.我方) || !string.IsNullOrEmpty(item.客户1) 
                                    || !string.IsNullOrEmpty(item.页数) || !string.IsNullOrEmpty(item.份数) 
                                    || !string.IsNullOrEmpty(item.是否复印件) || !string.IsNullOrEmpty(item.密级) 
                                    || !string.IsNullOrEmpty(item.保管期限) || !string.IsNullOrEmpty(item.档案类型) || !string.IsNullOrEmpty(item.档号))
                                {
                                    dataList.Add(item);
                                }
                            }                            
                            LogHelper.Info("dataList：" + JsonConvert.SerializeObject(dataList));
                            if (dataList != null && dataList.Count > 0)
                            {
                                #region 各字段集合                                
                                //归档人工号
                                var listGDRGH = dataList.Select(m => m.归档人工号).ToList();
                                LogHelper.Info("归档人工号list:" + JsonConvert.SerializeObject(listGDRGH));
                                //文件名称
                                var listWJMC = dataList.Select(m => m.文件名称).ToList();
                                LogHelper.Info("文件名称list:" + JsonConvert.SerializeObject(listWJMC));
                                //我方
                                var listWF = dataList.Select(m => m.我方).ToList();
                                LogHelper.Info("我方list:" + JsonConvert.SerializeObject(listWF));
                                //客户1
                                var listKH1 = dataList.Select(m => m.客户1).ToList();
                                LogHelper.Info("客户1list:" + JsonConvert.SerializeObject(listKH1));
                                //客户2
                                var listKH2 = dataList.Select(m => m.客户2).ToList();
                                LogHelper.Info("客户2list:" + JsonConvert.SerializeObject(listKH2));
                                //页数
                                var listYS = dataList.Select(m => m.页数).ToList();
                                LogHelper.Info("页数list:" + JsonConvert.SerializeObject(listYS));
                                //份数
                                var listFS = dataList.Select(m => m.份数).ToList();
                                LogHelper.Info("份数list:" + JsonConvert.SerializeObject(listFS));
                                //是否复印件
                                var listSFFYJ = dataList.Select(m => m.是否复印件).ToList();
                                LogHelper.Info("是否复印件list:" + JsonConvert.SerializeObject(listSFFYJ));
                                //密级
                                var listMJ = dataList.Select(m => m.密级).ToList();
                                LogHelper.Info("密级list:" + JsonConvert.SerializeObject(listMJ));
                                //保管期限
                                var listBGQX = dataList.Select(m => m.保管期限).ToList();
                                LogHelper.Info("保管期限list:" + JsonConvert.SerializeObject(listBGQX));
                                //档案类型
                                var listDALX = dataList.Select(m => m.档案类型).ToList();
                                LogHelper.Info("档案类型list:" + JsonConvert.SerializeObject(listDALX));
                                //档号
                                var listDH = dataList.Select(m => m.档号).ToList();
                                LogHelper.Info("档号list:" + JsonConvert.SerializeObject(listDH));
                                #endregion

                                #region 校验操作
                                Regex reg = new Regex("^\\d+$");
                                #region 归档人工号
                                LogHelper.Info("归档人工号begin");
                                int idxGDRGH = 1;
                                foreach (var item in listGDRGH)
                                {
                                    idxGDRGH++;
                                    //归档人工号不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：归档人工号不能为空\r\n", idxGDRGH);
                                    }
                                    else
                                    {
                                        //根据归档人工号查询用户是否存在
                                        int codeResult = DataDAL.GetOrgUserCountByCode(item.Trim());
                                        if (codeResult <= 0)
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：归档人工号{1}不存在\r\n", idxGDRGH, item);
                                        }
                                    }
                                }                          
                                LogHelper.Info("归档人工号end");
                                #endregion
                                
                                #region 文件名称
                                LogHelper.Info("文件名称begin");
                                int idxWJMC = 1;
                                foreach (var item in listWJMC)
                                {
                                    idxWJMC++;
                                    //文件名称不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：文件名称不能为空\r\n", idxWJMC);
                                    }
                                }
                                LogHelper.Info("文件名称end");
                                #endregion

                                #region 我方
                                LogHelper.Info("我方begin");
                                int idxWF = 1;
                                foreach (var item in listWF)
                                {
                                    idxWF++;
                                    //我方不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：我方不能为空\r\n", idxWF);
                                    }
                                    else
                                    {
                                        //根据我方查询是否存在
                                        int wfResult = DataDAL.GetWXGLBaseWFCountByItem(item.Trim());
                                        if (wfResult <= 0)
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：我方{1}不存在\r\n", idxWF, item);
                                        }
                                    }
                                }
                                LogHelper.Info("我方end");
                                #endregion

                                #region 客户1
                                LogHelper.Info("客户1begin");
                                int idxKH1 = 1;
                                foreach (var item in listKH1)
                                {
                                    idxKH1++;
                                    //客户1不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：客户1不能为空\r\n", idxKH1);
                                    }
                                    else
                                    {
                                        //根据客户1查询是否存在
                                        int kh1Result = DataDAL.GetWXGLBaseKH1CountByItem(item.Trim());
                                        if (kh1Result <= 0)
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：客户1{1}不存在\r\n", idxKH1, item);
                                        }
                                    }
                                }
                                LogHelper.Info("客户1end");
                                #endregion

                                #region 客户2
                                LogHelper.Info("客户2begin");
                                int idxKH2 = 1;
                                foreach (var item in listKH2)
                                {
                                    idxKH2++;
                                    //客户2非必填，如果填了就要验证是否存在
                                    if (!string.IsNullOrEmpty(item))
                                    {
                                        //根据客户2查询是否存在
                                        int kh2Result = DataDAL.GetWXGLBaseKH1CountByItem(item.Trim());
                                        if (kh2Result <= 0)
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：客户2{1}不存在\r\n", idxKH2, item);
                                        }
                                    }
                                }
                                LogHelper.Info("客户2end");
                                #endregion

                                #region 页数
                                LogHelper.Info("页数begin");
                                int idxYS = 1;
                                foreach (var item in listYS)
                                {
                                    idxYS++;
                                    //页数不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：页数不能为空\r\n", idxYS);
                                    }
                                    else
                                    {
                                        //页数只能输入整数
                                        Match m = reg.Match(item.Trim());
                                        if (!m.Success)
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：页数{1}不是整数\r\n", idxYS, item);
                                        }
                                    }
                                }
                                LogHelper.Info("页数end");
                                #endregion

                                #region 份数
                                LogHelper.Info("份数begin");
                                int idxFS = 1;
                                foreach (var item in listFS)
                                {
                                    idxFS++;
                                    //份数不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：份数不能为空\r\n", idxFS);
                                    }
                                    else
                                    {
                                        //份数只能输入整数
                                        Match m = reg.Match(item.Trim());
                                        if (!m.Success)
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：份数{1}不是整数\r\n", idxFS, item);
                                        }
                                    }
                                }
                                LogHelper.Info("份数end");
                                #endregion

                                #region 是否复印件
                                LogHelper.Info("是否复印件begin");
                                int idxSFFYJ = 1;
                                foreach (var item in listSFFYJ)
                                {
                                    idxSFFYJ++;
                                    //是否复印件不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：是否复印件不能为空\r\n", idxSFFYJ);
                                    }
                                    else
                                    {
                                        //是否复印件只能输入（是/否）
                                        string isCopy = item.Trim();
                                        if (!isCopy.Equals("是") && !isCopy.Equals("否"))
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：是否复印件只能输入是或否\r\n", idxSFFYJ);
                                        }
                                    }
                                }
                                LogHelper.Info("是否复印件end");
                                #endregion

                                #region 密级
                                LogHelper.Info("密级begin");
                                int idxMJ = 1;                             
                                foreach (var item in listMJ)
                                {
                                    idxMJ++;
                                    //密级不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：密级不能为空\r\n", idxMJ);
                                    }
                                    else
                                    {
                                        //根据密级查询是否存在
                                        int levelResult = DataDAL.GetWXGLBaseCountByItem(item.Trim());
                                        if (levelResult <= 0)
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：密级{1}不存在\r\n", idxMJ, item);
                                        }
                                    }
                                }
                                LogHelper.Info("密级end");
                                #endregion

                                #region 保管期限
                                LogHelper.Info("保管期限begin");
                                int idxBGQX = 1;
                                foreach (var item in listBGQX)
                                {
                                    idxBGQX++;
                                    //保管期限不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：保管期限不能为空\r\n", idxBGQX);
                                    }
                                    else
                                    {
                                        //根据保管期限查询是否存在
                                        int datesResult = DataDAL.GetAccessSaveYearCountByTime(item.Trim());
                                        if (datesResult <= 0)
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：保管期限{1}不存在\r\n", idxBGQX, item);
                                        }
                                    }
                                }
                                LogHelper.Info("保管期限end");
                                #endregion

                                #region 档案类型
                                LogHelper.Info("档案类型begin");
                                int idxDALX = 1;
                                foreach (var item in listDALX)
                                {
                                    idxDALX++;
                                    //档案类型不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：档案类型不能为空\r\n", idxDALX);
                                    }
                                }
                                LogHelper.Info("档案类型end");
                                #endregion

                                #region 档号
                                LogHelper.Info("档号begin");
                                int idxDH = 1;
                                List<string> result = new List<string>();
                                foreach (var item in listDH)
                                {
                                    idxDH++;
                                    //档号不能为空
                                    if (string.IsNullOrEmpty(item))
                                    {
                                        success = false;
                                        msg += string.Format("行号{0}：档号不能为空\r\n", idxDH);
                                    }
                                    else
                                    {
                                        //档号不能重复
                                        string record = item.Trim();
                                        if (result.Contains(record))
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：档号{1}重复\r\n", idxDH, record);
                                        }
                                        else
                                        {
                                            result.Add(record);
                                        }
                                        //根据档号查询是否存在
                                        int recordResult = DataDAL.GetAccessArchiveInfoByRecord(record);
                                        if (recordResult > 0)
                                        {
                                            success = false;
                                            msg += string.Format("行号{0}：档号{1}已存在\r\n", idxDH, record);
                                        }
                                    }
                                }
                                LogHelper.Info("档号end");
                                #endregion

                                #region 提示信息汇总
                                if (!success)
                                {
                                    msg = JsonConvert.SerializeObject(msg);
                                    context.Response.Write(msg);
                                    return;
                                }
                                #endregion
                                #endregion

                                #region 入库操作
                                //批次号（生成规则：BAT+年月日+操作人工号+4位随机码）
                                string randomBatchNo = "BAT" + DateTime.Now.ToString("yyyyMMdd") + orgUser.user_code + RandomHelper.GenerateRandomCode(4);
                                LogHelper.Info("批次号："+ randomBatchNo);

                                foreach (var item in dataList)
                                {
                                    LogHelper.Info("item：" + JsonConvert.SerializeObject(item));

                                    AccessArchive model = new AccessArchive();
                                    DateTime nowDateTime = DateTime.Now;
                                    //根据归档人工号获取用户信息
                                    OrgUser GDUser = DataDAL.GetOrgUserByCode(item.归档人工号.Trim());
                                    LogHelper.Info("归档人信息：" + JsonConvert.SerializeObject(GDUser));
                                    //根据职位Id获取部门信息
                                    OrgDepartment GDDept = DataDAL.GetOrgDepartmentByPositionId(GDUser.position_id);
                                    LogHelper.Info("归档人部门：" + JsonConvert.SerializeObject(GDDept));
                                    //根据密级获取Id
                                    WXGLBase levelBase = DataDAL.GetWXGLBaseByItem(item.密级.Trim());
                                    LogHelper.Info("密级：" + JsonConvert.SerializeObject(levelBase));
                                    //根据保管期限获取Id
                                    AccessSaveYear SaveYear = DataDAL.GetAccessSaveYearByTime(item.保管期限.Trim());
                                    LogHelper.Info("保管期限：" + JsonConvert.SerializeObject(SaveYear));
                                    //根据我方获取Id
                                    WXGLBase wfBase = DataDAL.GetWXGLBaseWFByItem(item.我方.Trim());
                                    LogHelper.Info("我方：" + JsonConvert.SerializeObject(wfBase));
                                    //根据客户1获取Id
                                    WXGLBase kh1Base = DataDAL.GetWXGLBaseKH1ByItem(item.客户1.Trim());
                                    LogHelper.Info("客户1：" + JsonConvert.SerializeObject(kh1Base));
                                    //根据客户2获取Id
                                    WXGLBase kh2Base = new WXGLBase();
                                    if (!string.IsNullOrEmpty(item.客户2))
                                    {
                                        kh2Base = DataDAL.GetWXGLBaseKH1ByItem(item.客户2.Trim());
                                        LogHelper.Info("客户2：" + JsonConvert.SerializeObject(kh2Base));
                                    }

                                    model.Id = Guid.NewGuid().ToString();
                                    model.createTime = nowDateTime;
                                    model.modifiedTime = nowDateTime;
                                    model.createId = orgUser.user_id;
                                    model.updateId = orgUser.user_id;
                                    model.people = GDUser.user_name;
                                    model.Department = GDUser.dept_name;
                                    model.AccessionDate = nowDateTime;
                                    model.file = "[]";
                                    model.Record = item.档号.Trim();
                                    model.folderUrl = ConfigHelper.FolderUrl;
                                    model.level = levelBase.Id;//密级
                                    model.Page = item.页数.Trim();
                                    model.InventoryStatus = item.份数.Trim();
                                    model.dates = SaveYear.Id;
                                    model.ExecutionDate = string.IsNullOrEmpty(item.生效日期) ? nowDateTime : Convert.ToDateTime(item.生效日期);
                                    model.remarks = string.IsNullOrEmpty(item.备注) ? string.Empty : item.备注.Trim();
                                    model.TotalInventory = item.份数.Trim();
                                    model.ExistingInventory = item.份数.Trim();
                                    model.State = "2";
                                    model.InventoryType = item.档案类型.Trim();
                                    model.BatchNo = randomBatchNo;
                                    model.SaveTime = nowDateTime;
                                    model.OperationPeople = orgUser.user_account;
                                    model.Unit = GDDept.dept_name;
                                    model.UnitId = GDDept.dept_id;
                                    model.ContractName = item.文件名称.Trim();
                                    model.ProjectName = string.IsNullOrEmpty(item.项目名称) ? string.Empty : item.项目名称.Trim();
                                    model.Number = item.份数.Trim();
                                    model.ContractNo = string.IsNullOrEmpty(item.文件编号) ? string.Empty : item.文件编号.Trim();
                                    model.JiaFang = wfBase.Id;//我方
                                    model.ProjectNo = string.IsNullOrEmpty(item.项目编号) ? string.Empty : item.项目编号.Trim();
                                    model.YiFang = kh1Base.Id;//客户1
                                    model.IsCopy = item.是否复印件.Trim().Equals("是") ? "0" : "1";
                                    model.Code = item.归档人工号.Trim();
                                    model.ArchiveWay = "1";
                                    model.SafekeepingTime = "0";
                                    model.BingFang = string.IsNullOrEmpty(item.客户2) ? string.Empty : kh2Base.Id;//客户2
                                    LogHelper.Info("model：" + JsonConvert.SerializeObject(model));
                                    try
                                    {
                                        int res = DataDAL.InsertAccessArchive(model);
                                        if (res > 0)
                                        {
                                            #region 导入成功写日志
                                            AccessOperationLog modelLog = new AccessOperationLog();
                                            modelLog.OperationDataId = model.Id;
                                            modelLog.OperationType = "批量导入";
                                            modelLog.OperationPeople = orgUser.user_account;
                                            modelLog.OperationDataName = model.ContractName;
                                            modelLog.OperationEdit = string.Empty;
                                            modelLog.OperationBack = string.Empty;
                                            modelLog.createTime = nowDateTime;
                                            modelLog.BatchNo = model.BatchNo;
                                            modelLog.BorrowPeople = string.Empty;
                                            modelLog.ArchivePeople = model.people;
                                            modelLog.BorrowPeopleDept = string.Empty;
                                            modelLog.BorrowPeopleUnit = string.Empty;
                                            modelLog.ArchivePeopleDept = model.Department;
                                            modelLog.ArchivePeopleUnit = model.Unit;
                                            modelLog.ArchiveCode = model.Code;
                                            modelLog.BorrowCode= string.Empty;
                                            LogHelper.Info("modelLog：" + JsonConvert.SerializeObject(modelLog));
                                            DataDAL.InsertAccessOperationLog(modelLog);                                            
                                            #endregion
                                        }
                                        else
                                        {
                                            LogHelper.Info("导入失败：" + JsonConvert.SerializeObject(model));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.Info("导入异常：" + ex.Message + ex.StackTrace);
                                        msg = JsonConvert.SerializeObject("导入异常，请查看错误日志");
                                        context.Response.Write(msg);
                                    }
                                }
                                LogHelper.Info("导入完成");
                                msg = JsonConvert.SerializeObject("导入完成");
                                context.Response.Write(msg);
                                
                                #endregion
                            }
                            else
                            {
                                LogHelper.Info("获取Excel数据为空");
                                msg = JsonConvert.SerializeObject("获取Excel数据为空");
                                context.Response.Write(msg);
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        msg = JsonConvert.SerializeObject("获取操作人信息失败，请重新登录");
                        context.Response.Write(msg);
                    }
                }
                else
                {
                    msg = JsonConvert.SerializeObject("token失效，请重新登录");
                    context.Response.Write(msg);
                }
            }
            else
            {
                LogHelper.Info("token为空，请重新登录");
                msg = JsonConvert.SerializeObject("token为空，请重新登录");
                context.Response.Write(msg);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}